const router = require('koa-router')();

//查询
router.get('/list',async ctx => {

    // 查第一页的数据  pagenum=1  limit=2
    try{
        let {pagenum=1,limit=2} = ctx.query;
        let startIndex = (pagenum - 1)*limit;

        let totalData = await ctx.mysql.query('select count(*) from userlist');

        console.log(totalData[0]['count(*)'])

        let data = await ctx.mysql.query(`select * from userlist limit ${startIndex},${limit}`);
        ctx.body = {
            code:1,
            data,
            total:totalData[0]['count(*)']
        }
    }catch(e){
        ctx.body = {
            code:0,
            msg:e
        }
    }
})

//添加 axios.post('/add',{username,password,address,idCard,phone,create_time})

router.post('/add',async ctx => {
    let {username,password,address,idCard,phone} = ctx.request.body;
    if(username && password && idCard){  //容错处理
        //库里查询是否存在
        let userData = await ctx.mysql.query('select * from userlist where idCard=?',[idCard]);
        if(userData.length){
            //已经存在
            ctx.body = {
                code:3,
                msg:'此人已存在'
            }
        }else{
            let create_time = new Date();
            try{
                await ctx.mysql.query('insert into userlist (username,password,address,idCard,phone,create_time) values (?,?,?,?,?,?)',[username,password,address,idCard,phone,create_time])
                ctx.body = {
                    code:1,
                    msg:'添加成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'缺失参数'
        }
    }    
})

//删除

router.get('/del',async ctx => {
    let {id} = ctx.query;
    if(id || id === 0){
        try{
            await ctx.mysql.query('delete from userlist where id=?',[id]);
            ctx.body = {
                code:1,
                msg:'删除成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'缺失参数'
        }
    }
})

//修改
router.post('/edit',async ctx => {
    let {username,password,address,idCard,phone,id} = ctx.request.body;
    if(username && password && idCard && id){
        try{
            let create_time = new Date();
            await ctx.mysql.query('update userlist set username=?,password=?,address=?,idCard=?,phone=?,create_time=? where id=?',[username,password,address,idCard,phone,create_time,id])
            ctx.body = {
                code:1,
                msg:'修改成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            mgs:'丢失参数'
        }
    }
})

module.exports = router